package com.ssl.design.strategy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定义策略工厂，这里继承InitializingBean，实现afterPropertiesSet方法，可以完美的根据类型获取注入的Bean对象，然后
 * 放到Map种；实现ApplicationContextAware是为了获取ApplicationContext
 */
@Component
public class CertServiceFactory implements InitializingBean, ApplicationContextAware {
    private static final Map<String, CertService> CERT_SERVICE_MAP = new ConcurrentHashMap<>(8);

    private ApplicationContext applicationContext;

    public CertService getCertService(String proxyType) {
        return CERT_SERVICE_MAP.get(proxyType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(CertService.class).values().forEach(
                certService -> CERT_SERVICE_MAP.put(certService.proxyType(), certService)
        );
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
